package org.light.shiroauth.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.InterVarUtil;
import org.light.utils.StringUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class ChangePasswordUser extends Verb implements EasyUIPositions {
	
	public static String generateChangePasswordSql(Domain domain) throws Exception{
		String result = "update " +domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain) +" set ";
		result += domain.getActive().getFieldTableColumName() + "=" + domain.getDomainActiveStr()+ ",";
		result += domain.findFieldByFixedName("password").getFieldTableColumName() +  " = #{"+ domain.findFieldByFixedName("password").getLowerFirstFieldName()+"},";
		result += domain.findFieldByFixedName("salt").getFieldTableColumName() +  " = #{"+ domain.findFieldByFixedName("salt").getLowerFirstFieldName()+"},";
		result += domain.findFieldByFixedName("loginFailure").getFieldTableColumName() + " = 0 ";
		result += "where " + domain.findFieldByFixedName("userName").getFieldTableColumName() + " = #{" +domain.findFieldByFixedName("userName").getLowerFirstFieldName() + "}";
		return result;
	}
	
	public static String generateChangePasswordOracleSql(Domain domain) throws Exception{
		String result = "update " +domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain) +" set ";
		result += domain.getActive().getFieldTableColumName() + "=" + domain.getDomainActiveInteger()+ ",";
		result += domain.findFieldByFixedName("password").getFieldTableColumName() +  " = #{"+ domain.findFieldByFixedName("password").getLowerFirstFieldName()+"},";
		result += domain.findFieldByFixedName("salt").getFieldTableColumName() +  " = #{"+ domain.findFieldByFixedName("salt").getLowerFirstFieldName()+"},";
		result += domain.findFieldByFixedName("loginFailure").getFieldTableColumName() + " = 0 ";
		result += "where " + domain.findFieldByFixedName("userName").getFieldTableColumName() + " = #{" +domain.findFieldByFixedName("userName").getLowerFirstFieldName() + "}";
		return result;
	}
	
	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+StringUtil.capFirst(this.domain.getStandardName()));		
			method.setNoContainer(true);
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(100L,1,"<update id=\""+StringUtil.lowerFirst(this.getVerbName())+"\" parameterType=\""+this.domain.getFullName()+"\">"));
			if ("Oracle".equalsIgnoreCase(this.dbType)) {
				list.add(new Statement(200L,2, generateChangePasswordOracleSql(domain)));
			}else {
				list.add(new Statement(200L,2, generateChangePasswordSql(domain)));
			}
			list.add(new Statement(300L,1,"</update>"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("Boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("Boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport("org.springframework.transaction.annotation.Transactional");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addMetaData("Override");		
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
					
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,2, InterVarUtil.DB.dao.getVarName()+ ".changePassword"+domain.getStandardName()+"("+domain.getLowerFirstDomainName()+");"));
			list.add(new Statement(2000L,2,"return true;"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}

	public ChangePasswordUser(){
		super();
		this.dbType = "MariaDB";
		this.setLabel("修改用户密码");
	}
	
	public ChangePasswordUser(String dbType){
		super();
		this.dbType = dbType;
		this.setLabel("修改用户密码");
	}
	
	public ChangePasswordUser(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("ChangePasswordUser");
		this.setVerbName("ChangePassword"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("修改用户密码");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Change Password");
	}
	
	public ChangePasswordUser(Domain domain,String dbType) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("ChangePasswordUser");
		this.setVerbName("ChangePassword"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("修改用户密码");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("ChangePasswordUser");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+this.domain.getCapFirstDomainName());
			method.setReturnType(new Type("Map<String,Object>"));
			method.setThrowException(true);
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addAdditionalImport(this.domain.getPackageToken()+ ".shiro.UserRegisteAndLogin");
			method.addSignature(new Signature(1,this.domain.findFieldByFixedName("userName").getLowerFirstFieldName(),"String"));
			method.addSignature(new Signature(2,"old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName(),"String"));
			method.addSignature(new Signature(3,this.domain.findFieldByFixedName("password").getLowerFirstFieldName(),"String"));
			method.addMetaData("RequestMapping(value = \"/changePassword"+this.domain.getCapFirstDomainName()+"\", method = RequestMethod.POST)");
	
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,2,"Map<String,Object> result = new TreeMap<String,Object>();"));
			sList.add(new Statement(2000L,2,""+this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+" = service.find"+this.domain.getCapFirstDomainName()+"By"+this.domain.getDomainName().getCapFirstFieldName()+"("+this.domain.getDomainName().getLowerFirstFieldName()+");"));
			sList.add(new Statement(3000L,2,"String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+");"));
			sList.add(new Statement(4000L,2,""+this.domain.getLowerFirstDomainName()+"."+this.domain.findFieldByFixedName("loginFailure").getSetterCallName()+"(0);"));
			sList.add(new Statement(5000L,2,""+this.domain.getLowerFirstDomainName()+"."+this.domain.findFieldByFixedName("salt").getSetterCallName()+"(saltAndCiphertext[0]);"));
			sList.add(new Statement(6000L,2,""+this.domain.getLowerFirstDomainName()+"."+this.domain.findFieldByFieldName(""+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"").getSetterCallName()+"(saltAndCiphertext[1]);"));
			sList.add(new Statement(7000L,2,""));
			sList.add(new Statement(8000L,2,"service.changePassword"+this.domain.getCapFirstDomainName()+"("+this.domain.getLowerFirstDomainName()+");"));
			sList.add(new Statement(9000L,2,"result.put(\"success\",true);"));
			sList.add(new Statement(10000L,2,"result.put(\"data\",null);"));
			sList.add(new Statement(11000L,2,""));
			sList.add(new Statement(12000L,2,"return result;"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("changePassword"+domain.getCapFirstDomainName());
			StatementList sList = new StatementList();

			sList.add(new Statement(1000L,0,"{"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(2000L,1,"text:'Change Password',"));
			}else {
				sList.add(new Statement(2000L,1,"text:'设置密码',"));	
			}			
			sList.add(new Statement(3000L,1,"iconCls:'icon-reload',"));
			sList.add(new Statement(4000L,1,"handler:function(){"));
			sList.add(new Statement(5000L,2,"var rows = $(\"#dg\").datagrid(\"getChecked\");"));
			sList.add(new Statement(6000L,2,"if (rows == undefined || rows == null || rows.length == 0 ){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(8000L,3,"return;"));
			sList.add(new Statement(9000L,2,"}"));
			sList.add(new Statement(10000L,2,"if (rows.length > 1) {"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(12000L,3,"return;"));
			sList.add(new Statement(13000L,2,"}"));
			sList.add(new Statement(14000L,2,"$(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").val(rows[0][\""+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\"]);"));
			sList.add(new Statement(15000L,2,"$('#wchangePassword').window('open');"));
			sList.add(new Statement(16000L,1,"}"));
			sList.add(new Statement(17000L,0,"}"));
			block.setMethodStatementList(sList);
			return block;			
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("changePassword"+domain.getCapFirstDomainName());			

			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(2000L,1,"var "+this.domain.getDomainName().getLowerFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#"+this.domain.getDomainName().getLowerFirstFieldName()+"\").val();"));
			sList.add(new Statement(3000L,1,"var "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val();"));
			sList.add(new Statement(4000L,1,"var confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val();"));
			sList.add(new Statement(5000L,1,"if (isBlank("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+")||isBlank(confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(6000L,2,"$.messager.alert(\"Error\",\"New password can not be empty.\",\"error\");"));
			}else {
				sList.add(new Statement(6000L,2,"$.messager.alert(\"错误\",\"新密码不可为空！\",\"error\");"));
			}
			sList.add(new Statement(7000L,2,"return;"));
			sList.add(new Statement(8000L,1,"}"));
			sList.add(new Statement(9000L,1,"if ("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"!=confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(10000L,2,"$.messager.alert(\"Error\",\"New password did not match.\",\"error\");"));
			}else {
				sList.add(new Statement(10000L,2,"$.messager.alert(\"错误\",\"新密码不匹配！\",\"error\");"));
			}
			sList.add(new Statement(11000L,2,"return;"));
			sList.add(new Statement(12000L,1,"}"));
			sList.add(new Statement(13000L,1,"$.ajax({"));
			sList.add(new Statement(14000L,2,"type: \"post\","));
			sList.add(new Statement(15000L,2,"url: \"../"+this.domain.getControllerPackagePrefix()+this.domain.getLowerFirstDomainName()+this.domain.getControllerNamingSuffix()+"/changePassword"+this.domain.getCapFirstDomainName()+"\","));
			sList.add(new Statement(16000L,2,"data:  {"));
			sList.add(new Statement(17000L,3,""+this.domain.getDomainName().getLowerFirstFieldName()+":"+this.domain.getDomainName().getLowerFirstFieldName()+","));
			sList.add(new Statement(18000L,3,""+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+":hex_sha1("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"),"));
			sList.add(new Statement(19000L,2,"},"));
			sList.add(new Statement(20000L,2,"dataType: 'json',"));
			sList.add(new Statement(21000L,2,"success: function(data, textStatus) {"));
			sList.add(new Statement(22000L,3,"if (data.success) {"));
			sList.add(new Statement(23000L,4,"$(\"#wchangePassword\").window(\"close\");"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(24000L,4,"$.messager.alert(\"Success\",\"Changed password successfully.\",\"info\");"));
			}else {
				sList.add(new Statement(24000L,4,"$.messager.alert(\"成功\",\"成功修改密码！\",\"info\");"));
			}
			sList.add(new Statement(25000L,3,"}"));
			sList.add(new Statement(26000L,2,"},"));
			sList.add(new Statement(27000L,2,"complete : function(XMLHttpRequest, textStatus) {"));
			sList.add(new Statement(28000L,2,"},"));
			sList.add(new Statement(29000L,2,"error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sList.add(new Statement(30000L,3,"alert(\"Error:\"+textStatus);"));
			sList.add(new Statement(31000L,3,"alert(errorThrown.toString());"));
			sList.add(new Statement(32000L,2,"}"));
			sList.add(new Statement(33000L,1,"});"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changePassword"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			
			List<Writeable> sList = new ArrayList<Writeable>();			
			sList.add(new Statement(1000L,2,"for (int i=0;i<db.size();i++){"));
			sList.add(new Statement(2000L,3,"if (db.get(i).get"+this.domain.getDomainId().getCapFirstFieldName()+"() == "+this.domain.getLowerFirstDomainName()+".get"+this.domain.getDomainId().getCapFirstFieldName()+"()){"));
			sList.add(new Statement(3000L,4,"db.get(i).set"+this.domain.findFieldByFixedName("salt").getCapFirstFieldName()+"("+this.domain.getLowerFirstDomainName()+".get"+this.domain.findFieldByFixedName("salt").getCapFirstFieldName()+"());"));
			sList.add(new Statement(4000L,4,"db.get(i).set"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"("+this.domain.getLowerFirstDomainName()+".get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"());"));
			sList.add(new Statement(5000L,4,"db.get(i).set"+this.domain.findFieldByFixedName("loginFailure").getCapFirstFieldName()+"(0);"));
			sList.add(new Statement(6000L,3,"}"));
			sList.add(new Statement(7000L,2,"}"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			
			return method;
		}
	}
}
